package com.android.powerbankpad.network;

import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

public class CustomOkHttpClient {
    public static OkHttpClient getCustomOkHttpClient() {
        // 创建一个自定义的 OkHttpClient，它信任所有 SSL 证书
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        try {
            // 创建一个信任所有 SSL 证书的 SSL Socket Factory
            javax.net.ssl.TrustManager[] trustAllCertificates = new javax.net.ssl.TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCertificates, new java.security.SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCertificates[0]);
            builder.hostnameVerifier((hostname, session) -> true); // 忽略主机名验证
            // 设置 OkHttpClient 的超时时间
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
            builder.writeTimeout(30, TimeUnit.SECONDS);
            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
